package airportCoordinationMonitor;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;

import org.json.JSONObject;

public class IncomingHandler implements Runnable{

	private int monitor_port;
	private List<PacketLog> pings;
	private Lock lock;
	
	private final int BUFFER_SIZE = 1024*1024;
	
	public IncomingHandler(int mp, List<PacketLog> p, Lock l)
	{
		monitor_port = mp;
		pings = p;
		lock = l;
	}
	
	public void run()
	{
		System.out.print("IncomingHandler running\n");
		while (true)
		{
			DatagramSocket sock = null;
			try{
				sock = new DatagramSocket(monitor_port);
			}catch(Exception e){ System.out.print("FATAL ERROR. Error opening monitor port: " + e.getMessage() + "\n"); System.exit(666); }
			byte[] buffer = new byte[BUFFER_SIZE];
			DatagramPacket packet = new DatagramPacket(buffer, BUFFER_SIZE); 
			
			while (true)
			{
				try{
					sock.receive(packet);
				}catch(Exception e){ System.out.print("Error recieving packet: " + e.getMessage() + "\n"); continue; }
				System.out.print("Reciving packet\n");
				
				JSONObject msg = null;
				int id = 0;
				String message = new String(buffer, 0, packet.getLength());
				try{
					msg = new JSONObject(message);
					id = msg.getInt("id");
				}catch(Exception e){ System.out.print("Error reading packet: " + e.getMessage() + "\n"); continue; }
				
				lock.lock();
				int pack = Collections.binarySearch(pings, new PacketLog(id, 0));
				if (pack >= 0) pings.remove(pack);
				else System.out.print("Warning: id not found on logs.\n");
				lock.unlock();
				
				packet.setLength(BUFFER_SIZE);
			}
		}
	}
}
